<template>
  <div class="customer">
    <ai-main>
      <div class="customer-wrapper">
        <div class="datePicker">
          <ai-panel>
            <div slot="title">
              <span>{{ currDate | timeFormat }}</span><span>（客群管理）</span>
            </div>
            <div slot="picker" class="picker">
              <div class="block">
                <el-date-picker v-model="currDate"
                                align="right"
                                type="date"
                                placeholder="选择日期"
                                size="mini"
                                @change="dateChanged"
                                :clearable="false"
                                :picker-options="datePickerOption">
                </el-date-picker>
              </div>
            </div>
            <div slot="content">
              <div class="cusnumber">
                <el-row>
                  <el-col :span="6">
                    <div class="grid-content bg-purple-dark">
                      <div class="item">
                        <div class="detail">
                          <span>
                            <count-up :startVal="0"
                                      :endVal="customer_num || 0 "
                                      :decimals="0"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit">个</span>
                        </div>
                        <div class="txt text-label">当日进店人数</div>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content bg-purple-dark">
                      <div class="item">
                        <div class="detail">
                          <span>
                            <count-up :startVal="0"
                                      :endVal="goIntoshopsRate"
                                      :decimals="2"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit">%</span>
                        </div>
                        <div class="txt text-label">当日进店转化率</div>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content bg-purple-dark">
                      <div class="item">
                        <div class="detail">
                          <span>
                            <count-up :startVal="0"
                                      :endVal="buyRate"
                                      :decimals="2"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit">%</span>
                        </div>
                        <div class="txt text-label">当日购买转化率</div>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content bg-purple-dark">
                      <div class="item">
                        <div class="detail">
                          <span v-if="minutes>=60">
                            <count-up :startVal="0"
                                      :endVal="parseInt(minutes/60) || 0"
                                      :decimals="0"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit" v-if="minutes>=60">时</span>
                          <span>
                            <count-up :startVal="0"
                                      :endVal="minutes%60 || 0"
                                      :decimals="0"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit">分</span>
                          <span>
                            <count-up :startVal="0"
                                      :endVal="seconds || 0"
                                      :decimals="0"
                                      :duration="0.5"
                                      :options="cuConfig">
                            </count-up>
                          </span>
                          <span class="unit">秒</span>
                        </div>
                        <div class="txt text-label">平均停留时长</div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </ai-panel>
          <div class="cuscharts">
            <ec-gender-pie :gender="gender"></ec-gender-pie>
            <ec-age-bar :ageCharts="ageCharts"></ec-age-bar>
            <ec-cus-flow :passengerFlow="passengerFlow" :hourOfToday="hourOfToday"></ec-cus-flow>
            <ec-stay-time-bar :residenceTime="residenceTime"></ec-stay-time-bar>
          </div>
        </div>
      </div>
      <div class="customer-photo-list">
        <ai-panel>
          <span slot="title">用户图像</span>
          <div slot="picker">
            <div class="picker-wrapper">
              <el-time-picker is-range
                              v-model="currPickerDate"
                              class="picker-component"
                              size="mini"
                              align="right"
                              range-separator="至"
                              format="HH:mm"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              @change="(value) => { this.handleSelectChange(value, this) }"
                              placeholder="选择时间范围">
              </el-time-picker>
              <el-select v-model="currPickerAge"
                         size="mini"
                         class="select-component"
                         @change="(value) => { this.handleSelectChange(value, this) }"
                         placeholder="请选择年龄段">
                <el-option v-for="item in ageOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model="currPickerGender"
                         size="mini"
                         class="select-component"
                         @change="(value) => { this.handleSelectChange(value, this) }"
                         placeholder="请选择性别">
                <el-option v-for="item in genderOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div slot="content" class="content">
            <el-table :data="userAvatarListData"
                      empty-text="暂无数据"
                      style="width: 100%">
              <el-table-column prop="entry_at"
                               label="入店时间"
                               align="left"
                               width="230">
              </el-table-column>
              <el-table-column label="顾客人数"
                               align="left"
                               width="230">
                <template slot-scope="scope">{{ scope.row.amount + ' 人' }}</template>
              </el-table-column>
              <el-table-column label="顾客图像"
                               align="left">
                <template slot-scope="scope">
                  <img :src="item['avatar']" alt="avatar"
                       v-for="(item, index) in scope.row.customers"
                       :key="index"
                       width="60" height="60"
                       class="item-user-avatar-img"
                       @click="navToUserInfo(item['id'],item['line_id'])">
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              @size-change="(value) => { this.handleSelectChange(value, this, 'currPageSize') }"
              @current-change="(value) => { this.handleSelectChange(value, this) }"
              :current-page.sync="currPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next"
              :total="userAvatarListDataTotal"
              style="text-align:right">
            </el-pagination>
          </div>
        </ai-panel>
      </div>
    </ai-main>
  </div>
</template>

<script>
import { Row, Col, TimePicker, DatePicker, Select, Option, Table, TableColumn, Pagination } from 'element-ui'
import ICountUp from 'vue-countup-v2'
import Panel from '@/components/panel'
import Main from '@/components/main'
import genderPie from '@/components/echarts/genderPie/genderPie.vue'
import ageBar from '@/components/echarts/ageBar/ageBar.vue'
import cusFlow from '@/components/echarts/cusFlow/cusFlow.vue'
import stayTimeBar from '@/components/echarts/stayTimeBar/stayTimeBar.vue'
import { APIGetShopStatus, APIDailyStatus, APIGetUserAvatarList } from '@/api/customer'
import Moment from 'moment'

const _DEBOUNCE = require('lodash.debounce')

const selectAgeOptionValue = [
  [],
  [0, 17],
  [18, 23],
  [24, 30],
  [31, 40],
  [41, 50],
  [51, 60],
  [60, 100]
]

export default {
  name: 'customer',
  components: {
    elRow: Row,
    elCol: Col,
    elSelect: Select,
    elOption: Option,
    elTimePicker: TimePicker,
    elTable: Table,
    elTableColumn: TableColumn,
    elDatePicker: DatePicker,
    elPagination: Pagination,
    // 自定义组件
    countUp: ICountUp,
    aiPanel: Panel,
    ecGenderPie: genderPie,
    ecAgeBar: ageBar,
    ecCusFlow: cusFlow,
    ecStayTimeBar: stayTimeBar,
    aiMain: Main
  },
  created () {
    this.customerGetShopStatus()
    this.customerDailyStatus()
    this.APIGetUserAvatarList()
  },
  data () {
    return {
      // countUp 数字动态效果
      cuConfig: {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.'
      },
      value: '',
      datePickerOption: {
        disabledDate (time) {
          return time.getTime() > Moment() || time.getTime() < Moment().subtract(1, 'year')
        },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', Moment())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = Moment().subtract(1, 'day')
              picker.$emit('pick', date)
            }
          }
        ]
      },
      // 默认当天日期
      currDate: Moment().format('YYYY-MM-DD'),
      genderOptions: [
        {
          value: 0,
          label: '不限'
        },
        {
          value: 1,
          label: '男'
        },
        {
          value: 2,
          label: '女'
        }
      ],
      currPickerDate: null,
      currPickerGender: null,
      currPickerAge: null,
      ageOptions: [
        {
          value: 0,
          label: '不限'
        },
        {
          value: 1,
          label: '小于18岁'
        },
        {
          value: 2,
          label: '18-23岁'
        },
        {
          value: 3,
          label: '24-30岁'
        },
        {
          value: 4,
          label: '31-40岁'
        },
        {
          value: 5,
          label: '41-50岁'
        },
        {
          value: 6,
          label: '51-60岁'
        },
        {
          value: 7,
          label: '大于60岁'
        }
      ],
      customer_num: 0,
      goIntoshopsRate: 0,
      buyRate: 0,
      minutes: 0,
      seconds: 0,
      gender: [],
      ageCharts: [],
      passengerFlow: {},
      hourOfToday: 0,
      residenceTime: {},
      currPage: 1,
      currPageSize: 10,
      // 用户信息
      userAvatarListData: [],
      userAvatarListDataTotal: 0
    }
  },
  filters: {
    timeFormat (date) {
      return Moment(date).format('YYYY-MM-DD')
    }
  },
  methods: {
    customerGetShopStatus (date) {
      APIGetShopStatus(this.$store.getters.mallId, date)
        .then((res) => {
          const hourOfToday = Moment().format('HH')
          this.hourOfToday = Moment(date).format('YYYY-MM-DD') === Moment().format('YYYY-MM-DD') ? (hourOfToday * 1) : null
          this.ageCharts = res.data.stats ? res.data.stats.ageCharts || null : null
          this.residenceTime = res.data.stats ? res.data.stats.residenceTime || null : null
          this.passengerFlow = res.data.stats ? res.data.stats.passengerFlow || null : null
        })
    },
    customerDailyStatus (date) {
      APIDailyStatus(this.$store.getters.mallId, date)
        .then((res) => {
          if (res.data.stats) {
            const customer = res.data.stats
            this.customer_num = customer.customer_num * 1
            this.goIntoshopsRate = (customer.customer_num * 1 / customer.customer_num_all * 1) * 10000 / 100
            this.buyRate = (customer.dealed_times * 1 / customer.customer_times * 1) * 10000 / 100
            this.gender = [customer.gender_male * 1, customer.gender_female * 1]
            let avgSeconds = Math.round(customer.seconds / this.customer_num)
            this.minutes = parseInt(avgSeconds / 60)
            this.seconds = avgSeconds % 60
          } else {
            this.customer_num = 0
            this.goIntoshopsRate = 0
            this.buyRate = 0
            this.minutes = 0
            this.seconds = 0
            this.gender = null
          }
        })
    },
    dateChanged (date) {
      const pickerDate = Moment(date).format('YYYY-MM-DD')

      this.currPickerDate = null
      this.currPickerGender = null
      this.currPickerAge = null
      this.currPage = 1
      this.currPageSize = 10

      // 发送请求
      let params = {}
      params.start_date = Moment(this.currDate).hour(0).minute(0).seconds(0).format()
      params.end_date = Moment(this.currDate).hour(23).minute(59).seconds(0).format()
      params.page = this.currPage
      params.page_size = this.currPageSize
      this.APIGetUserAvatarList(params)
      this.customerGetShopStatus(pickerDate)
      this.customerDailyStatus(pickerDate)
    },
    navToUserInfo (customerId, lineId) {
      this.$router.push({
        name: 'customerInfo',
        query: {
          customerId,
          lineId
        }
      })
    },
    handleCurrentChange (page) {
      this.APIGetUserAvatarList({ page })
    },
    handleSelectChange: _DEBOUNCE((value, vm, key) => {
      if (key) {
        vm[key] = value
      }
      let params = {}
      params.start_date = Moment(vm.currDate).hour(0).minute(0).format()
      params.end_date = Moment(vm.currDate).hour(23).minute(59).format()
      if (vm.currPickerGender) {
        params.gender = vm.currPickerGender
      }
      if (vm.currPickerAge) {
        params.start_age = selectAgeOptionValue[vm.currPickerAge][0]
        params.end_age = selectAgeOptionValue[vm.currPickerAge][1]
      }
      if (vm.currPickerDate) {
        let year = Moment(vm.currDate).year()
        let month = Moment(vm.currDate).month()
        let date = Moment(vm.currDate).date()

        let stime = Moment(vm.currPickerDate[0]).year(year).month(month).date(date)
        let etime = Moment(vm.currPickerDate[1]).year(year).month(month).date(date)
        // params.start_date = Moment(params.start_age).seconds(0).format()

        params.start_date = stime.seconds(0).format()
        params.end_date = etime.seconds(59).format()
      }
      if (vm.currPage) {
        params.page = vm.currPage
      }
      if (vm.currPageSize) {
        params.page_size = vm.currPageSize
      }
      vm.APIGetUserAvatarList(params)
    }, 2000),
    // api
    APIGetUserAvatarList (params) {
      APIGetUserAvatarList({ shop: this.$store.getters.mallId, params })
        .then((res) => {
          this.userAvatarListDataTotal = res.data.total
          this.userAvatarListData = res.data.data || []
        })
    }
  }
}
</script>

<style scoped lang="less">
.customer {
  .customer-wrapper {
    box-sizing: border-box;
    box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
    .panel-components {
      box-shadow: 0;
      margin-bottom: 0;
    }
    .picker {
      text-align: right;
      .el-input {
        width: 100%;
        max-width: 220px;
        .el-input__inner {
          &:hover {
            background-color: #f2f2f2 !important;
          }
        }
      }
    }
    .cusnumber {
      .item {
        text-align: center;
        margin-bottom: 10px;
        .detail {
          font-size: 36px;
          height: 46px;
          line-height: 46px;
          margin-bottom: 5px;
          .unit {
            font-size: 14px;
          }
        }
        .text-label {
          color: #888 !important;
          font-size: 12px;
        }
      }
    }
    .cuscharts {
      padding: 20px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      background-color: #ffffff;
      margin-bottom: 20px;
    }
    .cusTable {
      padding: 20px;
      background-color: #ffffff;
      .cusHead {
        height: 30px;
        line-height: 30px;
        color: #666;
        span {
          font-size: 14px;
        }
        .text {
          vertical-align: center;
        }
        .right {
            display: flex;
            justify-content: flex-end;
            span {
              margin: 0 5px;
            }
        }
      }
      .cusBody {
        .el-row {
          height: 88px;
        }
      }
    }
  }
  .customer-photo-list {
    .picker-wrapper {
      width: 600px;
      height: 28px;
      .picker-component {
        float: right;
        width: 100%;
        max-width: 220px;
      }
      .select-component {
        float: right;
        margin-right: 20px;
        width: 100%;
        max-width: 150px;
      }
    }
    .item-user-avatar-img {
      margin-right: 20px;
      cursor: pointer;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
